<?php

class CompanyExtendController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array( 
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('weixininfo','appdownload'),
				'users'=>array('@'),
			), 
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
 
   /**
     * 微信模板信息
     * 
     **/
    public function actionWeixininfo()
    { 
      $models= CompanyExtend::model()->findAll("companyid=:companyid and type=:type",array(":companyid"=>Yii::app()->user->id,":type"=>"weixin"));
      $wxloginurl=Yii::app()->request->hostInfo.'/wxlogin&code='.md5(Yii::app()->params['private_key'].Yii::app()->user->id).Yii::app()->user->id; 

      $model=array(); 
      if(!empty($models)){
        foreach ($models as $key => $value) {
          $model[$value->keys]=$value->values;
        }
      } 

      if(!empty($_POST)){     
        //判断传递的名称为空或者是新建icon
        if(empty($_POST['wxname']) || (empty($_POST['owxicon'])&& empty($_FILES['wxicon']['name'])) ){
          $model=$_POST; 
          return $this->render('weixininfo',array(
            'model'=>$model,'message'=>'错误:请正确设置微信关注登陆信息','wxloginurl'=>'',
          ));
        }
        //判断上传的图片是否gif,jpg,png
        if(!$this->decide_image_file($_FILES['wxicon'])){
            $model=$_POST; 
            return $this->render('weixininfo',array(
              'model'=>$model,'message'=>'错误:图标格式仅支持gif,jpg,png。大小小于3M。','wxloginurl'=>$wxloginurl,
            )); 
        }
        
        //判断微信的名称是否改变
        //如果改变再判断是修改还是新增 
        $model['wxname']=$this->check_input_save($models,"weixin","wxname",$_POST['wxname'],(empty($model['wxname'])?'':$model['wxname']));
        
        //如果上传文件改变重新保存 
        $model['wxicon']=$this->check_image_save($models,$_FILES['wxicon'],'weixin','wxicon',$_POST['owxicon']);

        unset($_POST);
        return $this->render('weixininfo',array(
        'model'=>$model,'message'=>'设置微信关注登陆信息成功','wxloginurl'=>$wxloginurl,'code'=>1,
        ));

      } 
      if((empty($model['wxicon']) && empty($model['wxname']))?true:false){
         $wxloginurl="";
      }  
      $this->render('weixininfo',array(
         'model'=>$model,'wxloginurl'=>$wxloginurl,
      ));
    }

    /**
     * 下载app应用模板设置
     * 
     **/
    public function actionAppdownload()
    { 
      $models= CompanyExtend::model()->findAll("companyid=:companyid and type=:type",array(":companyid"=>Yii::app()->user->id,":type"=>"appdownload"));
      $model=array(); 
      if(!empty($models)){
           foreach ($models as $key => $value) {
            $model[$value->keys]=$value->values;
          }
      } 
      //判断是否是提交保存
      if(!empty($_POST)) { 
        //判断传递的名称为空或者是新建icon
        if(empty($_POST['appname']) || (empty($_POST['oappicon']) && empty($_FILES['appicon']['name'])) || empty($_POST['appcontent'])|| empty($_POST['appandroidurl'])|| empty($_POST['appiosurl'])){
          $model=$_POST; 
          return $this->render('appdownload',array(
            'model'=>$model,'message'=>'错误:请正确设置应用下载的信息',
          ));
        }

        if (!preg_match('/http:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is',$_POST['appandroidurl']) || !preg_match('/http:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is',$_POST['appiosurl']) ){
            $model=$_POST; 
            return $this->render('appdownload',array(
              'model'=>$model,'message'=>'错误:请正确设置android和ios的下载网址',
            ));
        }
        //判断上传的图片是否gif,jpg,png
        if(!$this->decide_image_file($_FILES['appicon'])){
            $model=$_POST; 
            return $this->render('appdownload',array(
              'model'=>$model,'message'=>'错误:图标格式仅支持gif,jpg,png。大小小于3M。',
            )); 
          }   
        //如果上传文件改变重新保存 
        $model['appicon']=$this->check_image_save($models,$_FILES['appicon'],'appdownload','appicon',$_POST['oappicon']);
        //判断名称是否改变 
        $model['appname']=$this->check_input_save($models,"appdownload","appname",$_POST['appname'],(empty($model['appname'])?'':$model['appname']));
        $model['appcontent']=$this->check_input_save($models,"appdownload","appcontent",$_POST['appcontent'],(empty($model['appcontent'])?'':$model['appcontent']));
        $model['appandroidurl']=$this->check_input_save($models,"appdownload","appandroidurl",$_POST['appandroidurl'],(empty($model['appandroidurl'])?'':$model['appandroidurl']));
        $model['appiosurl']=$this->check_input_save($models,"appdownload","appiosurl",$_POST['appiosurl'],(empty($model['appiosurl'])?'':$model['appiosurl']));
        // exit;
        unset($_POST);
        return $this->render('appdownload',array(
        'model'=>$model,'message'=>'设置应用下载登陆信息成功','code'=>1,
        ));

      }

      $this->render('appdownload',array(
          'model'=>$model,
      ));
    }

    /**
     * 判断内容是否是更新还是新增 
     **/
    private function check_input_save($models,$type,$key,$newcont,$oldcont)
    {
        //判断名称是否改变 
        if(0!==strcmp($newcont,$oldcont)){
          //如果改变再判断是修改还是新增 
          if(empty($oldcont)){ 
              $companyExtend=new CompanyExtend();
              $companyExtend->companyid=Yii::app()->user->id;
              $companyExtend->type=$type;
              $companyExtend->keys=$key;
              $companyExtend->values=$newcont;
              $companyExtend->save();  
          }else{ 
            foreach ($models as $key => $value) {
              if($value->keys==$key){
                $value->values=$newcont;
                $value->save();
              }
            }
          } 
          return $newcont; 
        }
        return $oldcont;
    }

    /**
     * 判断上传的文件是规格的格式和大小
     *
     * @return void
     * @author 
     **/
    private function decide_image_file($files)
    {
        $returns=true;
       //判断上传的图片是否gif,jpg,png
        if($files['error']==0 ){
            if((($files["type"] !== "image/gif")
            && ($files["type"] !== "image/jpeg")
            && ($files["type"] !== "image/pjpeg")
            && ($files["type"] !== "image/png")
            )|| ($files["size"] > (1024*1024*3))) { 
               $returns=false;
            } 
          }
        return $returns;
    }
    /**
     * 判断图片是否需要更新
     *  
     **/
    private function check_image_save($models,$files,$type,$key,$oldurl)
    {

        $returns=$oldurl;
        if($files['error']==0 ){
          $datetime=Yii::app()->format->formatDate(time());
          $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
          if (!file_exists($uploaddir)) {
            mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
          }
          $filename = md5(uniqid()); 
          $ext = substr($files['name'],strpos($files['name'],'.')+1);
          $uploadfile = $uploaddir . $filename . '.' . $ext; 

          move_uploaded_file($files["tmp_name"],$uploadfile);

          $newurl='/uploads/' .$datetime.'/'. $filename . '.' . $ext;

          //判断是否旧的logo，如果存在并删除就文件
          if(!empty($oldurl)&&file_exists(dirname(Yii::app()->basePath).$oldurl)){
            unlink(dirname(Yii::app()->basePath).$oldurl);
          }

          if(empty($oldurl)){
            $companyExtend=new CompanyExtend();
            $companyExtend->companyid=Yii::app()->user->id;
            $companyExtend->type=$type;
            $companyExtend->keys=$key;
            $companyExtend->values=$newurl;
            $companyExtend->save(); 
          }else{
            foreach ($models as $key => $value) {
              if($value->keys==$key){
              $value->values=$newurl;
              $value->save();
              }
            }
          }  
           $returns=$newurl;
        }
        return $returns;
    }

   /**
     * 判断传递进来的url是否能够访问 
     **/
    private function check_remote_file_exists($url) 
    { 
        $curl = curl_init($url); 
        // 不取回数据 
        curl_setopt($curl, CURLOPT_NOBODY, true); 
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); //不加这个会返回403，加了才返回正确的200，原因不明 
        // 发送请求 
        $result = curl_exec($curl); 
        $found = false; 
        // 如果请求没有发送失败 
        if ($result !== false)  { 
        // 再检查http响应码是否为200 
            $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); 
            if ($statusCode == 200){ 
                $found = true; 
            } 
        } 
        curl_close($curl); 
        return $found; 
    } 

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return CompanyExtend the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=CompanyExtend::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CompanyExtend $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='company-extend-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
